package com.aaa.sso.config;

import com.aaa.entity.User;
import com.aaa.utils.JwtUtils;
import com.aaa.vo.Result;
import com.alibaba.fastjson.JSON;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @program: aaa-his-parent
 * @description:
 * @author: 闫克起2
 * @create: 2023-12-07 11:10
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //指定认证的service类。
        auth.userDetailsService(userDetailsService)
                //指定密码加密器
            .passwordEncoder(passwordEncoder())
        ;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http.formLogin()
                 //登录处理路径
                 .loginProcessingUrl("/login")
                 //指定登录成功的处理器
                 .successHandler(successHandler())
                 //指定失败的处理器
                 .failureHandler(failureHandler())
                 .permitAll();
         //指定权限不足的处理器
         http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());

         //指定允许跨域
        http.cors();
        //指定禁用csrf
        http.csrf().disable();

        http.authorizeRequests().anyRequest().authenticated();


    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    private AuthenticationSuccessHandler successHandler(){
        return (request, response, authentication) -> {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            //根据当前账户生成jwt令牌
            String name = authentication.getName();
            System.out.println(authentication.getDetails());
            String token = JwtUtils.create(name);
            //根据令牌把用户信息以及权限放入redis中
            ValueOperations<String, String> forValue = redisTemplate.opsForValue();
            forValue.set("user:"+token,name,30, TimeUnit.MINUTES);


            Result<String> result=new Result<String>(200,"登录成功",token);
            writer.print(JSON.toJSONString(result));
            writer.flush();
            writer.close();
        };
    }

    private AuthenticationFailureHandler failureHandler(){
        return (request, response, exception) -> {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            Result<Void> result=new Result<Void>(500,"账户或密码错误",null);
            writer.print(JSON.toJSONString(result));
            writer.flush();
            writer.close();
        };
    }
    private AccessDeniedHandler accessDeniedHandler(){
        return (request, response, accessDeniedException) -> {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            Result<Void> result=new Result<Void>(401,"权限不足",null);
            writer.print(JSON.toJSONString(result));
            writer.flush();
            writer.close();
        };
    }
}
